package com.jifen.utils;

import java.text.DecimalFormat;

public class LonLatUtils {

    private static final double EARTH_RADIUS = 6378137;
    private static final double RAD = Math.PI / 180.0;

    /**
     * 根据两点间经纬度坐标（double值），计算两点间距离
     *
     * @param lng1
     * @param lat1
     * @param lng2
     * @param lat2
     * @return
     */
    public static String getDistance(double lng1, double lat1, double lng2, double lat2) {
        String distance = "";
        double radLat1 = lat1 * RAD;
        double radLat2 = lat2 * RAD;
        double a = radLat1 - radLat2;
        double b = (lng1 - lng2) * RAD;
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        if (s > 1000) {
            s = s / 1000;
            DecimalFormat df = new DecimalFormat("#.0");
            distance = df.format(s) + "km";
        } else {
            DecimalFormat df = new DecimalFormat("#");
            distance = df.format(s) + "m";
        }
        return distance;
    }

}
